//
//  AudioPlayer.m
//  ChatDemo
//
//  Created by 陈石 on 15/5/13.
//  Copyright (c) 2015年 陈石. All rights reserved.
//

#import "AudioPlayer.h"
#import "AppDelegate.h"

@interface AudioPlayer () <AVAudioPlayerDelegate>
@end

@implementation AudioPlayer

+ (AudioPlayer *)sharedInstance
{
    static AudioPlayer     *player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
    {
        player = [[AudioPlayer alloc] init];
    });
    return player;
}

- (void)playSongWithData:(NSData *)songData
{
    [self setupPlaySound];
    [self playSoundWithData:songData];
}

- (void)playSoundWithData:(NSData *)soundData
{
    if (_player)
    {
        [_player stop];
        _player.delegate = nil;
        _player = nil;
    }
    NSError *playerError;
    _player = [[AVAudioPlayer alloc] initWithData:soundData error:&playerError];
    _player.volume = 1.0f;
    if (_player == nil)
    {
        //NSLog(@"ERror creating player: %@", [playerError description]);
    }
    _player.delegate = self;
    [_player play];
    [self.delegate play];
}

- (void)setupPlaySound
{
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}

- (void)audioPlayerDidFinishPlaying:(AudioPlayer *)player successfully:(BOOL)flag
{
    [self.delegate finish];
}

- (void)stopSound
{
    if (_player && _player.isPlaying)
    {
        [_player stop];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [self.delegate finish];
}
@end
